﻿begin tran
update Muon set ngayGio_muon='1999-06-06' where isbn=1 and ma_cuonsach=3
waitfor delay '0:0:5' --wait for 5ms
update DocGia set ho=N'Võ' where ma_docgia=1
commit tran



















set tran isolation level repeatable read
select session_id, host_name, login_name, transaction_isolation_level from sys.dm_exec_sessions where original_login_name = 'sa'














--------------------FIX:-------------------------------
DECLARE @RetryCounter INT
SET @RetryCounter = 1
RETRY: -- gan nhan RETRY
BEGIN TRANSACTION
BEGIN TRY

	set tran isolation level repeatable read
	update Muon set ngayGio_muon='1999-06-06' where isbn=1 and ma_cuonsach=3
	waitfor delay '0:0:5' --cho 5ms
	update DocGia set ho=N'Võ' where ma_docgia=1

	COMMIT TRANSACTION
END TRY
BEGIN CATCH
	PRINT 'Deadlock xay ra, Rollback Transaction'
	ROLLBACK TRANSACTION
	DECLARE @DoRetry bit; -- quyet dinh thuc hien lai trans hay khong ?
	DECLARE @ErrorMessage varchar(500)
	SET @doRetry = 0;
	SET @ErrorMessage = ERROR_MESSAGE()
	IF ERROR_NUMBER() = 1205 -- Neu deadlock xay ra
	BEGIN
		SET @doRetry = 1; -- Set @doRetry =1 khi neu loi la deadlock
	END
	IF @DoRetry = 1
	BEGIN
		SET @RetryCounter = @RetryCounter + 1 -- tang Retry Counter len 1
		IF (@RetryCounter > 3) -- neu deadlock xay ra 3 lan
		BEGIN
		
			RAISERROR(@ErrorMessage, 18, 1) -- xuat thong bao la deadlock da xay ra 3 lan
		END
		ELSE -- neu trans chua thuc hien qua 3 lan
		BEGIN
			WAITFOR DELAY '00:00:5' -- cho 5 ms
			GOTO RETRY	-- thuc hien lai trans
		END
	END
	ELSE
	BEGIN
		RAISERROR(@ErrorMessage, 18, 1)
	END
END CATCH